package GoodsService

import (
	"context"
	"gdshop-font-api-go/app/request/GoodsReq"
	"gdshop-font-api-go/app/service/FenxiaoService"
	"gdshop-font-api-go/app/service/GoodsActivityService"
	"gdshop-font-api-go/library/response"
	"gdshop-font-api-go/library/tools"
	toolsDb "gdshop-font-api-go/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
)

func Details(ctx context.Context, parames *GoodsReq.Details) *response.JsonResponse {
	goodsModel, err := GetGoodsModel(ctx, parames.Id)
	if err != nil {
		return tools.GetErrNoRowsResponse(err, "成功，无数据", true)
	}

	// 取出规格
	goodsModel.Specs = getGoodsSpecs(ctx, parames.Id)
	// 商品是否收藏，用户未登陆或者没收藏都是返回false
	goodsModel.IsCollection = goodsIsCollection(ctx, parames.Id, int(parames.MemberId))
	resultMap := gconv.Map(goodsModel)
	// 获取活动
	tags, err := GoodsActivityService.GetGoodsActivityTagByGoodsId(ctx, parames.Id)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resultMap["tags"] = tags
	resultMap["attributes"] = getGoodsAttribute(ctx, parames.Id)
	resultMap["photo_base_url"] = g.Cfg().GetString("site.PhotoUrlProfix")
	resultMap["fenxiao_info"] = getGoodsFenxiaoInfo(ctx, int(parames.MemberId), parames.Id)
	// 删除多余的数据
	delete(resultMap, "create_at")
	delete(resultMap, "update_at")
	delete(resultMap, "display_sort")
	return response.SuccessByRequestMessageData(nil, "成功", resultMap)
}

func goodsIsCollection(ctx context.Context, goodsId int, memberId int) bool {
	if memberId < 1 || goodsId < 1 {
		return false
	}
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"member_collection").Where(g.Map{
		"member_id": memberId,
		"goods_id":  goodsId,
	}).Fields("1").Count()
	if err != nil {
		return false
	}

	return count > 0
}

func getGoodsFenxiaoInfo(ctx context.Context, memberId, goodsId int) g.Map {
	fanhui := g.Map{}

	fanhui["fenxiao_text"] = "佣金"

	config, err := FenxiaoService.GetConfig()
	if err != nil {
		fanhui["level_name"] = "一级"
	} else {
		if config.SelfPurchaseRebate == 1 {
			fanhui["level_name"] = "自购返"
		} else {
			fanhui["level_name"] = "一级"
		}
	}
	if memberId < 1 {
		fanhui["money"] = 0
	} else {
		fanhui["money"] = FenxiaoService.GetMemberGoodsDetailsBrokerage(ctx, memberId, goodsId)
	}

	return fanhui
}

func getGoodsAttribute(ctx context.Context, goodsId int) g.List {
	all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "goods_attribute").Where("attribute_type=1 AND goods_id = ?", goodsId).
		Fields("icon_name,icon_text").All()
	if err != nil {
		return g.List{}
	}

	return all.List()
}
